from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404

from user.models import User

from .models import Content

# Create your views here.
def index(request):
    return render(request, 'user/index.html')
def reg_view(request):
    if request.method == 'GET':
        return render(request, 'user/register.html')
    elif request.method == 'POST':
        data = request.POST
        username = data.get('username')
        password = data.get('password')
        password_2 = data.get('password_2')

        if not username or not password:
            return HttpResponse('用户名或密码不能为空!')
        elif User.objects.filter(username=username):
            return HttpResponse('用户名已存在!')
        elif password_2 != password:
            return HttpResponse('两次密码不一致!')

        user = User.objects.create_user(username=username,password=password)
        return HttpResponse(f'{user.username}创建成功!')


def login_view(request):
    if request.method == 'GET':
        return render(request, 'user/login.html')
    elif request.method == 'POST':
        data = request.POST
        username = data.get('username')
        password = data.get('password')

        if not username or not password:
            return HttpResponse('用户名或密码为空!')
        user=authenticate(username=username,password=password)
        if user is None:
            return HttpResponse('用户名或密码错误!')
        login(request,user)
        return render(request,'note/list_note.html',locals())
def logout_view(request):
    logout(request)
    return HttpResponse('退出登录成功')

@login_required
def wj_load(request):
    if request.method=='GET':
        return render(request,'user/update.html',locals())
    elif request.method=='POST':
        user_id=request.session['uid']
        uname=request.session['uname']
        # 使用 get() 方法获取用户对象
        user = get_object_or_404(User, id=user_id)

        # 确保请求中有文件上传
        if 'wj' in request.FILES:
            # 更新用户文件字段
            user.myfile = request.FILES['wj']
            # 保存用户对象
            user.save()
            return HttpResponse(f'更新成功  <a href="/user/user_view/">点击跳转到其他用户界面</a>')


# def wj_load(request, user_id):
#     if request.method == 'GET':
#         return render(request, 'user/update.html')
#     elif request.method == 'POST':
#         user = get_object_or_404(User, id=user_id)
#         if 'wj' in request.FILES:
#             user.myfile = request.FILES['wj']
#             user.save()
#             return HttpResponse('ok')
#         else:
#             return HttpResponse("No file selected.", status=400)



def user_view(request):
    users=User.objects.all()
    return render(request,'user/user_view.html',locals())